package com.myblog.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myblog.constant.CodeType;
import com.myblog.mapper.ArticleMapper;
import com.myblog.mapper.CategoryMapper;
import com.myblog.model.Article;
import com.myblog.model.Category;
import com.myblog.service.ArticleService;
import com.myblog.service.CategoryService;
import com.myblog.utils.DataMap;
import com.myblog.utils.JsonResult;
import com.myblog.utils.StringAndArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;


    @Autowired
    private ArticleMapper articleMapper;
    /**
     * 后台分类管理获取分类
     * @return
     */
    @Override
    public DataMap getCategories() {
        List<Category> categories = categoryMapper.selectAll();
        if (categories == null){
            return DataMap.fail(CodeType.CATEGORY_NOT_EXIST);
        }
        JSONObject resultJSON = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        for (Category category : categories) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("id",category.getId());
            jsonObject.put("categoryName",category.getCategoryName());
            jsonArray.add(jsonObject);
        }
        resultJSON.put("result",jsonArray);
        return DataMap.success().setData(resultJSON);
    }

    /**
     * 添加或删除分类
     * 通过传递过来的type判断
     * @param categoryName
     * @param type
     * @return
     */
    @Override
    @Transactional
    public DataMap updataCategory(String categoryName,int type) {
        //默认分类不存在
        int isExsitCategory = 0;
        //分类已存在
        if (categoryMapper.selectByName(categoryName) != null){
            isExsitCategory = 1;
        }
        //type=1，新增  type=2，删除
        //删除
        if (type == 2){
            if (isExsitCategory == 0){
                return DataMap.fail(CodeType.CATEGORY_NOT_EXIST);
            }
            //该分类下存在文章不能删除

            //删除
            categoryMapper.deleteCategory(categoryName);
            return DataMap.success(CodeType.DELETE_CATEGORY_SUCCESS);
        }
        //新增
        else {
            if(isExsitCategory == 1){
                return DataMap.fail(CodeType.CATEGORY_EXIST);
            }
            categoryMapper.addCategory(categoryName);
            return DataMap.success(CodeType.ADD_CATEGORY_SUCCESS);
        }
    }

    /**
     * 获取所有的分类名字
     * @return
     */
    @Override
    public DataMap findAllCategoriesName() {
        List<Category> categories = categoryMapper.selectAll();
        List<String> categoriesNames = new ArrayList<>();
        for (Category category : categories) {
            categoriesNames.add(category.getCategoryName());
        }
        return DataMap.success().setData(categoriesNames);
    }

    @Override
    public DataMap findCategoriesNameAndArticleNum() {
        List<Category> categories = categoryMapper.selectAll();
        JSONArray categoriesJson = new JSONArray();
        for (Category category : categories) {
            JSONObject jsonObject = new JSONObject();
            Integer numOfArticle = articleMapper.selectNumOfArticleByCategoryName(category.getCategoryName());
            jsonObject.put("categoryName",category.getCategoryName());
            jsonObject.put("categoryArticleNum",numOfArticle);
            categoriesJson.add(jsonObject);
        }

        JSONObject result = new JSONObject();
        result.put("result",categoriesJson);
        return DataMap.success().setData(result);
    }

    @Override
    public DataMap getCategoryArticle(Integer rows, Integer pageNum,String categoryName) {
        PageHelper.startPage(pageNum,rows);
        //查询文章，如果category为空，则返回所有
        List<Article> articles;
        if (categoryName.equals("")){
            categoryName = "全部分类";
            articles = articleMapper.selectAllArticle();
        }
        else {
            articles = articleMapper.selectArticleByCategoryName(categoryName);
        }
        PageInfo<Article> pageInfo = new PageInfo<>(articles);
        JSONArray articleJsons = new JSONArray();
        //封装数据
        for (Article article : articles) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("articleId",article.getArticleId());
            jsonObject.put("articleTitle",article.getArticleTitle());
            jsonObject.put("publishDate",article.getPublishDate());
            jsonObject.put("articleCategories",article.getArticleCategories());
            jsonObject.put("articleTags", StringAndArray.stringToArray(article.getArticleTags()));
            articleJsons.add(jsonObject);
        }

        JSONObject result = new JSONObject();
        result.put("result",articleJsons);
        result.put("category",categoryName);

        JSONObject pageJson = new JSONObject();
        pageJson.put("pageNum",pageInfo.getPageNum());
        pageJson.put("pageSize",pageInfo.getSize());
        pageJson.put("total",pageInfo.getTotal());
        pageJson.put("pages",pageInfo.getPages());
        pageJson.put("isFirstPage",pageInfo.isIsFirstPage());
        pageJson.put("isLastPage",pageInfo.isIsLastPage());

        result.put("pageInfo",pageJson);

        return DataMap.success().setData(result);
    }


}
